package com.huangmingfu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 黄名富
 * @Description: 命令队列
 * @需求描述: 学校发布通知，将在3周以后进行考试。 老师收到通知后，需要制定复习计划，学生收到通知后，则要开始复习了
 */
public class CommandQueuePattern {

    public static void main(String[] args) {
        Student student = new Student();
        Teacher teacher = new Teacher();
        Command teacherCommand = new TeacherCommand(teacher);
        Command studentCommand = new StudentCommand(student);

        CommandQueue commandQueue = new CommandQueue();
        commandQueue.addCommand(teacherCommand);
        commandQueue.addCommand(studentCommand);

        School school = new School();
        school.setCommandQueue(commandQueue);
        school.releaseTestNote("3周以后进行考试");
    }

    private static class School {
        private CommandQueue commandQueue;

        public void setCommandQueue(CommandQueue commandQueue) {
            this.commandQueue = commandQueue;
        }

        public void releaseTestNote(String content) {
            if (commandQueue != null) commandQueue.execute(content);
        }
    }

    private static class CommandQueue{
        private final List<Command> commandList = new ArrayList<>();

        public void addCommand(Command command) {
            commandList.add(command);
        }

        public void clearCommand() {
            commandList.clear();
        }

        public void execute(String content) {
            for (Command command : commandList) command.execute(content);
        }
    }

    private static abstract class Command {
        void execute(String content) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:sss");
            System.out.println("收到通知:" + content + "," + dateFormat.format(new Date()));
            invoke(content);
        }

        abstract void invoke(String content);
    }

    private static class TeacherCommand extends Command {

        private final Teacher teacher;

        public TeacherCommand(Teacher teacher) {
            this.teacher = teacher;
        }

        @Override
        void invoke(String content) {
            if (teacher != null) teacher.developPlan();
        }
    }

    private static class StudentCommand extends Command {

        private final Student student;

        public StudentCommand(Student student) {
            this.student = student;
        }

        @Override
        void invoke(String content) {
            if (student != null) student.review();
        }
    }

    private static class Teacher {
        public void developPlan() {
            System.out.println("老师开始制定复习计划");
        }
    }

    private static class Student {
        public void review() {
            System.out.println("学生开始复习");
        }
    }

}
